热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

`final`关键字相当于Python中的变量?-`final`keywordequivalentforvariablesinPython?

IcouldntfinddocumentationonanequivalentofJavasfinalinPython,istheresuchathing?我找不

I couldn't find documentation on an equivalent of Java's final in Python, is there such a thing?

我找不到关于Java的最终版本的文档,是不是有这样的东西?

I'm creating a snapshot of an object (used for restoration if anything fails); once this backup variable is assigned, it should not be modified -- a final-like feature in Python would be nice for this.

我正在创建一个对象的快照(如果有任何失败则用于恢复);一旦分配了这个备份变量,就不应该修改它 - Python中的类似最终功能对此很有用。

8 个解决方案

#1


47  

Having a variable in Java be final basically means that once you assign to a variable, you may not reassign that variable to point to another object. It actually doesn't mean that the object can't be modified. For example, the following Java code works perfectly well:

在Java中使用变量是最终的,这意味着一旦分配给变量,就不能将该变量重新分配给另一个对象。它实际上并不意味着无法修改对象。例如,以下Java代码运行良好:

public final List messages = new LinkedList();

public void addMessage()
{
    messages.add("Hello World!");  // this mutates the messages list
}

but the following wouldn't even compile:

但以下甚至不会编译:

public final List messages = new LinkedList();

public void changeMessages()
{
    messages = new ArrayList();  // can't change a final variable
}

So your question is about whether final exists in Python. It does not.

所以你的问题是关于Python中是否存在final。它不是。

However, Python does have immutable data structures. For example, while you can mutate a list, you can't mutate a tuple. You can mutate a set but not a frozenset, etc.

但是,Python确实具有不可变的数据结构。例如,虽然您可以改变列表,但您不能改变元组。你可以变异集但不是变形集等。

My advice would be to just not worry about enforcing non-mutation at the language level and simply concentrate on making sure that you don't write any code which mutates these objects after they're assigned.

我的建议是不要担心在语言层面强制执行非变异,而只是集中精力确保你不会编写任何代码,这些代码在分配后会改变这些对象。

#2


57  

There is no ``final'' equivalent in Python.

Python中没有“最终”的等价物。

But, to create read-only fields of class instances, you can use the property function.

但是,要创建类实例的只读字段,可以使用属性函数。

Edit: perhaps you want something like this:

编辑:也许你想要这样的东西:

class WriteOnceReadWhenever:
    def __setattr__(self, attr, value):
        if hasattr(self, attr):
            raise Exception("Attempting to alter read-only value")

        self.__dict__[attr] = value

#3


9  

An assign-once variable is a design issue. You design your application in a way that the variable is set once and once only.

一次性赋值变量是一个设计问题。您可以将变量设置为一次且仅设置一次的方式设计应用程序。

However, if you want run-time checking of your design, you can do it with a wrapper around the object.

但是,如果您希望对设计进行运行时检查,则可以使用对象周围的包装器来执行此操作。

class OnePingOnlyPleaseVassily( object ):
    def __init__( self ):
        self.value= None
    def set( self, value ):
        if self.value is not None:
            raise Exception( "Already set.")
        self.value= value

someStateMemo= OnePingOnlyPleaseVassily()
someStateMemo.set( aValue ) # works
someStateMemo.set( aValue ) # fails

That's clunky, but it will detect design problems at run time.

这很笨重,但它会在运行时检测到设计问题。

#4


7  

There is no such thing. In general, the Python attitude is "if you don't want this modified, just don't modify it". Clients of an API are unlikely to just poke around your undocumented internals anyway.

哪有这回事。一般来说,Python的态度是“如果你不想修改它,就不要修改它”。无论如何,API的客户都不太可能只是在你的无证内部。

You could, I suppose, work around this by using tuples or namedtuples for the relevant bits of your model, which are inherently immutable. That still doesn't help with any part of your model that has to be mutable of course.

我想,你可以通过使用元组或命名元组来处理模型的相关位,这本身就是不可变的。这仍然无助于你的模型的任何部分当然必须是可变的。

#5


6  

Python has no equivalent of "final". It doesn't have "public" and "protected" either, except by naming convention. It's not that "bondage and discipline".

Python没有“最终”的等价物。它除了命名约定外,没有“公共”和“受保护”。这不是“束缚和纪律”。

#6


5  

you can simulate something like that through the descriptor protocol, since it allows to define reading and setting a variable the way you wish.

您可以通过描述符协议模拟类似的东西,因为它允许按照您希望的方式定义读取和设置变量。

class Foo(object):

  @property
  def myvar(self):
     # return value here

  @myvar.setter
  def myvar(self, newvalue):
     # do nothing if some condition is met

a = Foo()
print a.myvar
a.myvar = 5 # does nothing if you don't want to

#7


3  

http://code.activestate.com/recipes/576527/ defines a freeze function, although it doesn't work perfectly.

http://code.activestate.com/recipes/576527/定义了一个冻结函数,虽然它不能很好地工作。

I would consider just leaving it mutable though.

我会考虑让它变得可变。

#8


0  

Although this is an old question, I figured I would add yet another potential option: You can also use assert to verify a variable is set to what you originally intended it to be set to – a double checking if you will. Although this is not the same as final in Java, it can be used to create a similar effect:

虽然这是一个老问题,但我想我还会添加另一个可能的选项:您还可以使用assert来验证变量是否设置为您最初设置的值 - 如果您愿意,则进行双重检查。虽然这与Java中的final不同,但它可用于创建类似的效果:

PI = 3.14
radius = 3

try:
    assert PI == 3.14
    print PI * radius**2
except AssertionError:
    print "Yikes."

As seen above, if PI were for some reason not set to 3.14, an AssertionError would be thrown, so a try/except block would probably be a wise addition. Regardless, it may come in handy depending on your situation.

如上所示,如果PI由于某种原因未设置为3.14,则会抛出AssertionError,因此try / except块可能是明智的补充。无论如何,根据您的情况,它可能会派上用场。


推荐阅读
author-avatar
springzhe7943
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有